package com.cgbl.cg.ui.course

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import com.cgbl.cg.BR
import com.cgbl.cg.R
import com.cgbl.cg.adapter.CourseMenuAdapter
import com.cgbl.cg.databinding.AppFragmentCourseMenuBinding
import com.cgbl.cg.view.FilterPop
import com.cgbl.cg.vm.course.CourseMenuFraViewModel
import com.lxj.xpopup.XPopup
import com.robot.base.base.activity.GLBaseFragment
import com.robot.base.model.CourseBean

class CourseMenuFragment : GLBaseFragment<AppFragmentCourseMenuBinding, CourseMenuFraViewModel>() {

    private lateinit var courseMenuAdapter: CourseMenuAdapter
    var typeTab = ""

    companion object {
        fun newInstance(typeTab: String): CourseMenuFragment {
            val fragment = CourseMenuFragment()
            val bundle = Bundle()
            bundle.putString("typeTab", typeTab)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun initContentView(
        inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?
    ): Int = R.layout.app_fragment_course_menu

    override fun initParam() {
        super.initParam()
        typeTab = arguments?.getString("typeTab") ?: ""
    }

    override fun initVariableId(): Int = BR.viewModel

    override fun initComponents() {
        initAdapter()
    }

    override fun initData() {
        super.initData()
        viewModel.categoryId = typeTab
        viewModel.initData()
        viewModel.fetchPageInfo()
    }


    private fun initAdapter() {
        courseMenuAdapter = CourseMenuAdapter()
        binding.recyclerView.apply {
            adapter = courseMenuAdapter
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()

        viewModel.uc.showFilter.observe(this) {
            val filterPop =
                FilterPop(requireContext(), viewModel.filterName.get() ?: "", viewModel.list)
            XPopup.Builder(requireContext()).atView(binding.tv1).asCustom(filterPop).show()

            filterPop.setConfirmClickListener {
                filterPop.dismiss()
                viewModel.filterName.set(it)
            }
        }

        binding.smartRefreshLayout.setOnRefreshListener {
            viewModel.refresh()
        }

        binding.smartRefreshLayout.setOnLoadMoreListener {
            viewModel.load()
        }

        viewModel.uc.refreshEvent.observe(this) {
            binding.smartRefreshLayout.finishRefresh()
            binding.smartRefreshLayout.finishLoadMore()
            binding.smartRefreshLayout.setEnableLoadMore(it != 1)
        }

        viewModel.uc.dataListEvent.observe(this) {
            if (viewModel.page == 1) {
                courseMenuAdapter.setNewInstance(it as MutableList<CourseBean>?)
            } else {
                courseMenuAdapter.addData(it)
            }
        }
    }

}